/*
 * @Author: yuki
 * @Date: 2025-10-25 22:19:51
 * @LastEditTime: 2025-10-26 16:23:51
 * @Description: 雪花算法
 */
import { Inject, Injectable } from '@nestjs/common';
import { Snowflake } from '@sapphire/snowflake';

import { AppConfigType, appConfig } from '@/config';

@Injectable()
export class SnowflakeService {
  private readonly snowflake: Snowflake;

  constructor(
    @Inject(appConfig.KEY)
    private readonly configService: AppConfigType
  ) {
    const epoch = this.configService.SNOWFLAKE_EPOCH;
    const workerId = this.configService.SNOWFLAKE_WORKER_ID;
    const processId = this.configService.SNOWFLAKE_PROCESS_ID;
    this.snowflake = new Snowflake(epoch);
    this.snowflake.workerId = workerId;
    this.snowflake.processId = processId;
  }

  /**
   * 生成雪花ID
   */
  generate(): bigint {
    return this.snowflake.generate();
  }

  /**
   * 解析雪花 ID
   * @param id 雪花 ID（字符串或 bigint）
   * @returns 解析后的信息
   */
  parseId(id: string | bigint): {
    timestamp: Date; // 生成时间（Date 对象）
    workerId: number;
    processId: number;
    increment: number;
  } {
    const parsed = this.snowflake.deconstruct(id);
    return {
      timestamp: new Date(Number(parsed.timestamp)),
      workerId: Number(parsed.workerId),
      processId: Number(parsed.processId),
      increment: Number(parsed.increment)
    };
  }
}
